package com.example.intermingle.config;

import com.example.intermingle.dto.ResourcesDto;
import com.example.intermingle.mapper.ResourcesMapper;
import com.example.intermingle.vo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @author 绿松石
 * @version V1.0
 * @Title UserRoleStorageConfig 比较用户权限信息，看需要访问url需要的角色权限
 * @Description
 * @date 2021年08月20日 08:57
 * @since V1.0
 */
@Component
public class UserRoleStorageConfig implements FilterInvocationSecurityMetadataSource {

    @Autowired
    ResourcesMapper resourcesMapper;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取当前要请求的url
        String url = ((FilterInvocation) o).getRequestUrl();
        if ( "/login_p".equals ( url ) ) {
            return null;
        }
        //查询所有的用户拥有的角色权限路径
        List<ResourcesDto> resources = resourcesMapper.selectAllByResources();
        for (ResourcesDto resourcesDto : resources) {
            if (antPathMatcher.match(resourcesDto.getUrl(), url)) {
                //取出查询出来的权限
                List<Role> roles = resourcesDto.getRoles();
                //设置数组长度
                String[] str = new String[roles.size()];
                //for循环把权限放入数组
                for (int i = 0; i < roles.size(); i++) {
                    str[i] = roles.get(i).getRoleAuthority();
                }
                //返回权限信息，这里返回的Security框架的SecurityConfig，不是自定义的config
                return SecurityConfig.createList(str);
            }
        }
        //返回登陆权限信息，这里返回的Security框架的SecurityConfig，不是自定义的config
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
